<template>
    <div class="page-container">
        <h1 class="page-title">出入量</h1>

        <div class="header">
            <div class="patient-info">
                <span style="color:#f56c6c;">当前病人：</span>
                <span style="color:#f56c6c;">{{ currentPatient }}</span>
            </div>
            <div class="date-range">
                <span>统计时间：</span>
                <el-date-picker v-model="dateRange" type="datetimerange" range-separator="–" start-placeholder="开始时间"
                    end-placeholder="结束时间" style="width:360px;" />
                <el-button type="primary" class="query-btn" @click="onQuery">查询</el-button>
                <el-button type="primary" class="query-btn" @click="goOut()">返回</el-button>
            </div>
        </div>

        <div class="charts-container">
            <div class="chart-section">
                <h2 class="section-title">入量统计</h2>
                <div class="chart-content" v-show="showCharts">
                    <div class="chart-area">
                        <div id="inChart" style="height:300px;width:300px;"></div>
                        <div class="total-volume">
                            <div class="label">总入量 (ml)</div>
                            <div class="value">{{ totalInput }}</div>
                        </div>
                    </div>
                    <div class="volume-list">
                        <template v-if="inData.length > 0">
                            <div v-for="(item, index) in inData" :key="index" class="volume-item">
                                <div class="item-info">
                                    <span class="dot" :style="{ backgroundColor: progressColors[index] }"></span>
                                    <span class="name">{{ item.name }}</span>
                                    <div class="progress-bar"
                                        :style="{ width: item.percent + '%', backgroundColor: progressColors[index] }">
                                    </div>
                                </div>
                                <span class="volume">{{ item.volume }}ml</span>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
            <div class="chart-section">
                <h2 class="section-title">出量统计</h2>
                <div class="chart-content" v-show="showCharts">
                    <div class="chart-area">
                        <div id="outChart" style="height:300px;width:300px;"></div>
                        <div class="total-volume">
                            <div class="label">总出量 (ml)</div>
                            <div class="value">{{ totalOutput }}</div>
                        </div>
                    </div>
                    <div class="volume-list">
                        <template v-if="outData.length > 0">
                            <div v-for="(item, index) in outData" :key="index" class="volume-item">
                                <div class="item-info">
                                    <span class="dot" :style="{ backgroundColor: progressColors[index] }"></span>
                                    <span class="name">{{ item.name }}</span>
                                    <div class="progress-bar"
                                        :style="{ width: item.percent + '%', backgroundColor: progressColors[index] }">
                                    </div>
                                </div>
                                <span class="volume">{{ item.volume }}ml</span>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsType } from 'echarts'
import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import http from '@/api/http'

const router = useRouter()
const route = useRoute()

const goOut = () => {
    router.push({
        path: "/SummaryOne"
    })
}

interface VolumeData {
    name: string
    volume: number
    percent: number
}

interface ChartInstance {
    inChart: EChartsType
    outChart: EChartsType
}

interface ListItem {
    adiName: string;
    inValue: number;
}

interface OutRecord {
    id: number;
    patientCode: string;
    outValue: number;
    outputName: string;
    unit: string;
    outDate: string;
    outPeople: string;
}

// 获取病人编号和姓名
const patientName = computed(() => route.query.name as string)

// 响应式状态
const dateRange = ref<[Date, Date] | null>(null)
const hasQueried = ref(false)

// 当前病人信息
const currentPatient = computed(() => patientName.value || '未知病人')

const inData = ref<VolumeData[]>([
    { name: '输液量', volume: 720, percent: 60 },
    { name: '饮品', volume: 240, percent: 20 },
    { name: '输血', volume: 144, percent: 12 },
    { name: '餐食', volume: 96, percent: 8 }
])
const outData = ref<VolumeData[]>([])
var listOut = ref<OutRecord[]>([])
const charts = ref<ChartInstance | null>(null)

const progressColors = ['#409EFF', '#FF9F51', '#975FE4', '#67C23A']

// 计算属性
const totalInput = computed(() => {
    return list.value.reduce((sum, item) => sum + (Number(item.inValue) || 0), 0)
})
const totalOutput = computed(() => {
    return listOut.value.reduce((sum, item) => sum + (Number(item.outValue) || 0), 0)
})

var list = ref<ListItem[]>([])

// 图表配置
const chartConfig = {
    tooltip: {
        trigger: 'item',
        formatter: '{b}: {d}%'
    },
    series: [{
        type: 'pie',
        radius: ['0%', '75%'],
        avoidLabelOverlap: false,
        itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
        },
        label: {
            show: true,
            position: 'inside',
            formatter: '{d}%',
            fontSize: 14,
            color: '#fff'
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 14,
                color: '#fff'
            }
        },
        labelLine: {
            show: false
        }
    }]
}

const showCharts = computed(() => {
    if (!hasQueried.value) return true;
    return (inData.value.length > 0 || outData.value.length > 0);
});

//查询入量信息
const getInRecord = () => {
    const patientCode = route.query.number;
    if (!patientCode) {
        console.error('未获取到患者编号');
        return;
    }
    const [start, end] = dateRange.value || [];
    http.get(
        '/api/DoctorManage/GetInRecords',
        undefined,
        false,
        {
            params: {
                patientCode: patientCode,
                firstTime: start ? dayjs(start).format('YYYY-MM-DD HH:mm:ss') : undefined,
                endTime: end ? dayjs(end).format('YYYY-MM-DD HH:mm:ss') : undefined
            }
        }
    ).then(res => {
        if (!res.data || res.data.length === 0) {
            inData.value = [];
            list.value = [];
        } else {
            list.value = res.data;
            updateChartData();
            if (totalInput.value === 0) {
                inData.value = [];
            }
        }
        updateCharts();
    })
    .catch(error => {
        inData.value = [];
        list.value = [];
        updateCharts();
        console.error("获取入量信息失败:", error);
    });
};

//查询出量信息
const getOutRecord = () => {
    const patientCode = route.query.number;
    if (!patientCode) {
        console.error('未获取到患者编号');
        return;
    }
    const [start, end] = dateRange.value || [];
    http.get(
        '/api/DoctorManage/GetOutRecords',
        undefined,
        false,
        {
            params: {
                patientCode: patientCode,
                firstTime: start ? dayjs(start).format('YYYY-MM-DD HH:mm:ss') : undefined,
                endTime: end ? dayjs(end).format('YYYY-MM-DD HH:mm:ss') : undefined
            }
        }
    ).then(res => {
        if (!res.data || res.data.length === 0) {
            outData.value = [];
            listOut.value = [];
        } else {
            const outRecords = Array.isArray(res.data) ? res.data : [res.data];
            listOut.value = outRecords;
            // 处理出量数据
            if (listOut.value && listOut.value.length > 0) {
                const groupedOutData = listOut.value.reduce((acc, curr) => {
                    if (!acc[curr.outputName]) {
                        acc[curr.outputName] = 0;
                    }
                    acc[curr.outputName] += Number(curr.outValue) || 0;
                    return acc;
                }, {} as Record<string, number>);
                const values = Object.values(groupedOutData).map(val => Number(val));
                const totalOut = values.reduce((a, b) => a + b, 0);
                const chartData = Object.entries(groupedOutData).map(([name, volume]) => {
                    const numVolume = Number(volume);
                    return {
                        name: name || '未知',
                        volume: numVolume,
                        percent: totalOut === 0 ? 0 : Math.round((numVolume / totalOut) * 100)
                    } as VolumeData;
                });
                outData.value = chartData;
            }
        }
        updateCharts();
    })
    .catch(error => {
        outData.value = [];
        updateCharts();
        console.error("获取出量信息失败:", error);
    });
};

// 更新图表数据
const updateChartData = () => {
    // 处理入量数据
    if (list.value && list.value.length > 0) {
        const groupedData = list.value.reduce((acc, curr) => {
            if (!acc[curr.adiName]) {
                acc[curr.adiName] = 0;
            }
            acc[curr.adiName] += curr.inValue;
            return acc;
        }, {} as Record<string, number>);

        const total = Object.values(groupedData).reduce((sum, curr) => sum + curr, 0);

        inData.value = Object.entries(groupedData).map(([name, volume]) => ({
            name,
            volume,
            percent: total === 0 ? 0 : Math.round((volume / total) * 100)
        }));

        if (charts.value) {
            charts.value.inChart.setOption({
                ...chartConfig,
                series: [{
                    ...chartConfig.series[0],
                    data: inData.value.length > 0 ? inData.value.map(item => ({
                        name: item.name,
                        value: item.volume
                    })) : [],
                    color: progressColors
                }]
            });
        }
    } else {
        inData.value = [];
        if (charts.value) {
            charts.value.inChart.setOption({
                ...chartConfig,
                series: [{
                    ...chartConfig.series[0],
                    data: [],
                    color: progressColors
                }]
            });
        }
    }
}

// 方法
const initCharts = () => {
    const inChart = echarts.init(document.getElementById('inChart') as HTMLElement)
    const outChart = echarts.init(document.getElementById('outChart') as HTMLElement)

    charts.value = { inChart, outChart }
    updateCharts()
}

const updateCharts = () => {
    // 重新初始化 outChart
    if (charts.value) {
        // 销毁旧实例
        charts.value.outChart.dispose();
        // 重新获取 DOM 并初始化
        charts.value.outChart = echarts.init(document.getElementById('outChart') as HTMLElement);
    } else {
        // 第一次初始化
        charts.value = {
            inChart: echarts.init(document.getElementById('inChart') as HTMLElement),
            outChart: echarts.init(document.getElementById('outChart') as HTMLElement)
        };
    }

    // 入量
    charts.value.inChart.clear();
    charts.value.inChart.setOption({
        ...chartConfig,
        series: [{
            ...chartConfig.series[0],
            data: inData.value.length > 0 ? inData.value.map(item => ({
                name: item.name,
                value: item.volume
            })) : [],
            color: progressColors
        }]
    });

    // 出量
    charts.value.outChart.clear();
    charts.value.outChart.setOption({
        ...chartConfig,
        series: [{
            ...chartConfig.series[0],
            data: outData.value.length > 0 ? outData.value.map(item => ({
                name: item.name,
                value: item.volume
            })) : [],
            color: progressColors
        }]
    });
};

const handleResize = () => {
    if (!charts.value) return
    Object.values(charts.value).forEach(chart => chart.resize())
}

// 监听路由参数变化
watch(
    () => route.query.number,
    (newVal) => {
        if (newVal) {
            // 清空之前的数据
            list.value = []
            inData.value = []
            listOut.value = []
            outData.value = []
            // 重新获取数据
            getInRecord()
            getOutRecord()
        }
    },
    { immediate: true }  // 立即执行一次
)

watch(showCharts, (val) => {
  if (val && charts.value) {
    charts.value.outChart.resize();
    charts.value.inChart.resize();
    updateCharts();
  }
});

// 生命周期钩子
onMounted(() => {
    initCharts()
    getOutRecord()
    window.addEventListener('resize', handleResize)
})

watch(() => route.query, (newId) => {
  if (newId) {
    initCharts()
    getOutRecord()
    getInRecord()
    window.addEventListener('resize', handleResize)
      }
})
 

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (charts.value) {
        Object.values(charts.value).forEach(chart => chart.dispose())
    }
})

function onQuery() {
    hasQueried.value = true;
    getInRecord();
    getOutRecord();
}
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.page-title {
    text-align: center;
    color: #333;
    margin-bottom: 30px;
}

.header {
    display: flex;
    align-items: center;
    margin-bottom: 40px;
    gap: 40px;
}

.patient-info {
    font-size: 16px;
}

.date-range {
    display: flex;
    align-items: center;
    gap: 12px;
}

.query-btn {
    background-color: #409EFF;
}

.charts-container {
    display: flex;
    gap: 40px;
    justify-content: space-between;
}

.chart-section {
    flex: 1;
}

.section-title {
    color: #409EFF;
    font-size: 20px;
    margin-bottom: 30px;
}

.chart-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.chart-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30px;
}

.total-volume {
    text-align: center;
    margin-top: 20px;
}

.total-volume .label {
    color: #666;
    margin-bottom: 10px;
}

.total-volume .value {
    font-size: 36px;
    font-weight: bold;
    color: #333;
}

.volume-list {
    width: 100%;
    max-width: 400px;
}

.volume-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    position: relative;
}

.item-info {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
}

.dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.progress-bar {
    position: absolute;
    height: 6px;
    border-radius: 3px;
    opacity: 0.2;
    bottom: -8px;
    left: 0;
}

.volume {
    margin-left: 20px;
    color: #333;
    font-weight: 500;
}

:deep(.el-button) {
    border-radius: 4px;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}
</style>